package notwork;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer_1 {
    ServerSocket serverSocket=null;

    public TcpEchoServer_1(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("启动服务器");


        ExecutorService executorService= Executors.newCachedThreadPool();

        while (true){
            Socket socket=serverSocket.accept();
            executorService.submit(()->{
                processConnectiong(socket);
            });
        }
    }

    private void processConnectiong(Socket socket) {
        System.out.printf("客户端[%s  %d]上线!\n",socket.getInetAddress(),socket.getPort());
        try (InputStream input=socket.getInputStream();
             OutputStream output=socket.getOutputStream()
        ){
            Scanner scanner=new Scanner(input);
            PrintWriter printWriter=new PrintWriter(output);

            while(true){
                if(!scanner.hasNext()){
                    System.out.printf("客户端[ip:%s  port:%d]下线!\n" ,socket.getInetAddress(),socket.getPort());
                    break;
                }
                String request=scanner.next();
                String reponse=process(request);
                printWriter.println(reponse);
                printWriter.flush();
                System.out.println();
                System.out.printf("[ip:%s    port:%d]  req:%s    rep:%s",socket.getInetAddress(),socket.getPort(),request,reponse);
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer_1 tcpEchoClient_1=new TcpEchoServer_1(9090);
        tcpEchoClient_1.start();

    }

}

